package com.tk.exam.service;


import com.github.pagehelper.PageInfo;
import com.tk.exam.config.properties.SystemProperties;
import com.tk.exam.dao.TkFileDao;
import com.tk.exam.domain.TkFile;
import com.tk.exam.domain.TkFileExample;
import com.tk.exam.domain.TkFileExample;
import com.tk.exam.mapper.TkFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class TkFileService {
    public final static String TYPE_OFF_LINE="exam";

    @Autowired
    SystemProperties systemProperties;
    @Autowired
    TkFileMapper tkFileMapper;
    @Autowired
    private TkFileDao tkFileDao;


    public int saveTkFile(TkFile tkFile) {
        tkFileMapper.insert(tkFile);
        return tkFile.getId();
    }

    public TkFile getTkFile(int id) {
        return tkFileMapper.selectByPrimaryKey(id);
    }

    public PageInfo<TkFile> getTkFileWithPage(int examId){
        return tkFileDao.getOfflinePaperByExamIdWithPage(examId);
    }
    /**
     * @param entityId:
     * @param fileIds:
     * @Description: 批量修改entityId, 适用于新增试题无主键ID场景
     * @Date: 2019-06-19 14:44
     * @Return: void
     */
    public void updateEntityId(int entityId, List fileIds) {
        //更新
        tkFileMapper.updateEntityId(entityId, fileIds);
        //查询废弃的
        TkFileExample example = new TkFileExample();
        example.or().andIdNotIn(fileIds).andEntityIdEqualTo(entityId);
        List<TkFile> list = tkFileMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            return;
        }
        //删除文件
        List<Integer> idList = new ArrayList<>();
        for (TkFile tkFile : list) {
            idList.add(tkFile.getId());
            File file = new File(systemProperties.getFileUploadPath() + File.separator + tkFile.getFilePath());
            if (file.exists()) {
                File parentFile = file.getParentFile();
                file.delete();
                if (parentFile.listFiles().length == 0) {
                    parentFile.delete();
                }
            }
        }
        //删除废弃数据
        example = new TkFileExample();
        example.or().andIdIn(idList);
        tkFileMapper.deleteByExample(example);
    }
}
